from django.shortcuts import render,HttpResponse,redirect,reverse
from .models import User
from course.models import Course
from  course.models import  Category
from django.http import StreamingHttpResponse
import os
import re

# Create your views here.
def huiqu(request):
    user_id = ''
    user_account = ''
    try:
        session_user = request.session['session_user']
        user_id = session_user.get('id')
        user_account = session_user.get('account')
    except:
        user_id ='0'
        user_account = '0'

    ret= {'user_id': user_id, "user_account": user_account}
    return ret

def index(request):
    data_list = []
    categorys = Category.objects.all()
    for category in categorys:
        # data_list['cat_name'] = category.cat_name
        # data_list['courses'] = category.sender_set.all()
        data_list.append(
            {
                'cat_name': category.cat_name,
                'data_yuan': category.sender_set.all()}
                          )

    context ={'data_list':data_list}
    return render(request,'index.html',context)


def regiter(request):
    '''
    注册数据收集
    :param request:
    :return:
    '''
    return render(request,'regiter.html')


def regiter_do(request):
    '''
    注册数据入库
    :param request:
    :return:
    '''
    info = ''
    account = request.POST.get('account')#获取到用户名
    password = request.POST.get('password') #密码

    try:
        user_exists = User.objects.filter(account=account).exists()
        if not user_exists:
            user = User(account=account,password=password)
            user.save()
            request.session['session_user'] = {'id':user.id,'account':user.account}
            info = '恭喜您注册成功'
        else:
            info = '账号已存在'
    except:
        info = '服务器异常'
    finally:
        pass
    context = {"info": info}
    return render(request,'regiter_do.html',context)


def login_handler(request):
    return render(request,'login.html')


def login_do_handler(request):
    account = request.POST.get('account')  # 获取到用户名
    password = request.POST.get('password')  # 密码

    try:
        user_exists = User.objects.filter(account=account, password=password)
        if  user_exists:
            user = user_exists
            request.session['session_user'] = {'id': user[0].id, 'account': user[0].account}
            info = '登陆成功'
        else:
            info = '登陆失败；请查看登陆信息是否正确'
    except:
        info = '服务器异常'
    finally:
        pass
    context = {"info": info}
    return render(request, 'login_do.html', context)


def js_login(request):
    user_id = ''
    user_account= ''
    try:
        session_user = request.session['session_user']
        user_id = session_user.get('id')
        user_account = session_user.get('account')
    except:
        pass
    context ={'user_id':user_id,"user_account":user_account}
    return render(request,'js_login.html',context,content_type='text/javascript')


def center(request):
    user = huiqu(request)
    if user['user_id'] =='0':
        title = '请先登陆'
        nr = '请先登陆'
        context = jieguo(title, nr)
        return  render(request,'jieguo.html',context)
    else:
        user_info = User.objects.get(id = user['user_id'])
        context = {'user_info':user_info}
        return  render(request,'center.html',context)


def loginout(request):
    request.session.clear()
    info = '退出成功'
    context = {"info": info}
    return render(request,'regiter_do.html',context)


def course(request):
    return None

def jieguo(title,info):

    context = {
        'title': title,
        'info': info
    }
    return  context

def buy_course_handler(request,course_id):
    title =''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr ='请先登陆；在购买'
    else:
        user = User.objects.get(id = session_zhi['user_id']) #获取user信息
        cou_ = Course.objects.get(id = course_id) #获取 课程信息
        if(user.money < cou_.price):
            title = '余额不足'
            nr = '您的余额是：'+str(user.money)+';余额不足'
        else:
            user.money = user.money - cou_.price
            user.buyer_set.add(cou_)
            user.save()
            title ='购买成功'
            nr ='购买成功'
            try:
                cou_.carshop.remove(user)
            except:
                pass
            return redirect(reverse('list_book'))

    context = jieguo(title,nr)
    return  render(request,'jieguo.html',context)


def shop_car_handler(request,course_id):
    title =''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr ='请先登陆；加入购物车'
    else:
        user = User.objects.get(id = session_zhi['user_id']) #获取user信息
        cou_ = Course.objects.get(id = course_id) #获取 课程信息
        user.carshop_set.add(cou_)
        return redirect(reverse('list_shopcar'))

    context = jieguo(title,nr)
    return  render(request,'jieguo.html',context)


def videoStream_handler(request,course_id):
    # 定义读取视频的生成器
    def read_video(filepath,length,offset):
        with open(filepath,'rb') as f:
            # 跳过offset个字节
            f.seek(offset)
            while True:
                # 读取指定长度的数据
                data = f.read(length)
                # 如果有数据-->生成数据
                if data:yield data
                # 如果没有数据-->跳出循环
                else:break
    # context = request.context
    try:
        # 根据id得到课程
        course = Course.objects.get(id=course_id)
        # 得到当前登录的session_user
        session_user = request.session['session_user']
        # 得到用户是否购买课程
        boolean_buyed = User.objects.filter(id=session_user.get('id'),buyer_set__id=course_id).exists()
        # 如果用户购买了课程，则有购买权限
        if boolean_buyed:
            # context['course'] = course
            # 视频文件的大小
            size = os.path.getsize(course.video.__str__())
            print(size)
            # 请求头中的range
            request_range = request.headers.get('range')
            # 得到客户端想得到数据的起始位置
            start_bytes = re.findall('=(\d+)-',request_range)
            start_bytes = int(start_bytes[0]) if start_bytes else 0
            # 定义数据终止位置
            last_bytes = start_bytes + 1024 * 1024
            last_bytes = min(last_bytes,size-1)
            # 数据长度
            length = last_bytes - start_bytes + 1
            # 构造response对象
            response = StreamingHttpResponse(
                read_video(
                    course.video.__str__(),
                    length=length,
                    offset=start_bytes,
                ),
                status=206,
            )
            # 设置响应字节流的长度
            response['Content-Length'] = str(length)
            # Content-Range：bytes 起始字节位-终止字节位/总字节位
            response['Content-Range'] = 'bytes %s-%s/%s' % (start_bytes,last_bytes,size)
            return response
        # 如果没有购买，跳转到课程详细页
        else:
            return redirect(reverse('index_course',args=(course.id,)))
    except:
        return HttpResponse(status=404)


def user_video_handler(request,course_id):
    title =''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr ='请先登陆；'
    else:
        user = User.objects.get(id = session_zhi['user_id'])
        list = user.buyer_set.get(id = course_id)
        context = {"list":list}
        return render(request, 'video.html',context)
    context = jieguo(title,nr)
    return  render(request,'jieguo.html',context)



def list_book_handler(request):
    title =''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr ='请先登陆；'
    else:
        user = User.objects.get(id = session_zhi['user_id'])
        list = user.buyer_set.all()
        context = {"list":list}
        return  render(request,'list_book.html',context)
    context = jieguo(title,nr)
    return  render(request,'jieguo.html',context)


def list_shop_car_handler(request):
    title = ''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr = '请先登陆；'
    else:
        user = User.objects.get(id=session_zhi['user_id'])
        list = user.carshop_set.all()
        context = {"list": list}
        return render(request, 'list_car.html', context)
    context = jieguo(title, nr)
    return render(request, 'jieguo.html', context)


def center_do_handler(request):
    password = request.POST.get('password')#密码
    username = request.POST.get("username")#姓名
    gender   = request.POST.get('gender') #性别
    tel      = request.POST.get('tel') #姓名

    title =''
    nr = ''
    session_zhi = huiqu(request)
    # print(type(session_zhi),session_zhi)
    if session_zhi['user_id'] == '0':
        title = '请先登陆'
        nr ='请先登陆；'
    else:
        user = User.objects.get(id = session_zhi['user_id'])
        user.password = password
        user.username = username
        user.gender =gender
        user.tel =tel
        user.save()
        return redirect(reverse('user_center'))
    context = jieguo(title,nr)
    return  render(request,'jieguo.html',context)
